package com.cheyun.netsalev3.viewmodel

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.lifecycle.MutableLiveData
import com.cheyun.netsalev3.MyApplication
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.bean.HomeAppParam
import com.cheyun.netsalev3.tencenttim.utils.DemoLog
import com.cheyun.netsalev3.utils.FunctionUtils
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.utils.ToastUtil
import com.cheyun.netsalev3.view.*
import com.cheyun.netsalev3.view.aftersale.AfterSaleActivity
import com.cheyun.netsalev3.view.aftersale.AfterSaleDriveActivity
import com.cheyun.netsalev3.view.drivelist.DriveListActivity
import com.cheyun.netsalev3.view.orderlist.OrderListActivity
import com.cheyun.netsalev3.view.orderquanyi.OrderQuanyiActivity
import com.cheyunkeji.er.Constants
import com.cheyunkeji.er.activity.SplashActivity
import com.cheyunkeji.er.activity.evaluate.EvaluateHomePageActivity
import com.cheyunkeji.er.activity.fast_evaluate.FastEvaluateActivity
import com.cheyunkeji.er.app.GlobalConfig
import com.cheyunkeji.er.app.UserInfoManager
import com.cheyunkeji.er.bean.UserInfo
import com.cheyunkeji.er.bean.UserPermissions
import com.cheyunkeji.er.bean.evaluate.CarTempAttrList
import com.cheyunkeji.er.http.ApiClient
import com.cheyunkeji.er.http.HttpConstants
import com.cheyunkeji.er.http.RespCallback
import com.cheyunkeji.er.utils.ChannelInfoUtil
import com.cheyunkeji.er.utils.SerializeUtil
import com.cheyunkeji.er.view.SToast
import com.dou361.dialogui.DialogUIUtils
import com.google.gson.Gson
import com.zhy.http.okhttp.callback.StringCallback
import okhttp3.Call
import okhttp3.Request
import org.json.JSONException
import org.json.JSONObject
import java.net.SocketException
import java.net.UnknownHostException


/**
 * @author Michael
 * @date  2018/12/19 - 16:03.
 */
class HomeAppFragmentViewModel : BaseViewModel() {

    var showlistData = MutableLiveData<List<HomeAppParam>>()


    //话术库
    var huashuku = true
    //素材库
    var shucaiku = true
    //金融计算器
    var calc = true
    //车型对比
    var chexingduibi = true
    //试驾看板
    var driveBlock = true


    var toast1 = MutableLiveData<String>()

    var list = mutableListOf<HomeAppParam>()
    init {
        bindData()
//        checkErPermissions()
    }

    fun bindData(){
        var loginData = MySharedPreferences.getLoginData()

//        var start = loginData?.channel?.settings?.storage?.state ?: 0
//        loginData?.member?.apps?.stock?.apply {
//            for (i in this) {
//                if (i == 1 && start == 1) {
//                    statkun = true
//                }
//            }
//        }
//        loginData?.channel?.settings?.storage?.state?.apply {
//            statkun = (this == 1)
//        }
//        loginData?.member?.apps?.receive?.apply {
//            for (i in this) {
//                if (i == 1) {
//                    dengji = true
//                }
//                if (i == 2) {
//                    jiedai = true
//                }
//            }
//        }
//        loginData?.member?.apps?.chance?.apply {
//            for (i in this) {
//                if (i.equals("1401")){
//                    fail = true
//                }
//            }
//        }
//        analysis = false
//        loginData?.member?.apps?.analysis?.apply {
//            for (i in this) {
//                if (i.equals("1101")){
//                    analysis = true
//                }
//            }
//        }
//        order = false
//        loginData?.member?.apps?.order?.apply {
//            for (i in this) {
//                if (i.equals("1")){
//                    order = true
//                }
//            }
//        }
//
//        loginData?.member?.isadmin?.apply {
//            if(this==1){
//                dengji = true
//                jiedai = true
//                statkun = true
//                fail = true
//                analysis = true
//                order = true
//                calc = true
//                aftersale_maintenance = true
//                aftersale_drive = true
//            }
//        }
//        loginData?.channel?.settings?.receive?.apply {
//            if(this == 1){
//                jiedai = false
//            }
//        }
//        //app 集团端通道不显示 ：到店管理，客流接待，客服回访。
//        loginData?.channel?.isgroup?.apply {
//            if(this.equals("1")){
//                dengji = false
//                jiedai = false
//                statkun = false
//            }
//        }
//
//        //分析报表
//        //判断是否是VIP
//        //非VIP全部置灰
//        //VIP  如果是系统管理员，isadmin = 1， 全显示。 如果不是系统管理员， 按权限来
//
//        //非VIP版本显示功能   工具里只显示“ 战败管理 ”
//        var hasAuthorization = MySharedPreferences.hasAuthorization()
//        if(!hasAuthorization){
//            //库存管理
//            statkunHui = true
//            //到店管理
//            dengjiHui = true
//            //客流接待
//            jiedaiHui = true
//            //数据分析
//            analysisHui = true
//            //七日强转
//            qiangHui = true
//        }
////        else{
////            fail = true
////        }
//
//        statkunHui = true
//
////        var isDrive = MySharedPreferences.getIsDrive()
//        loginData?.channel?.is_driving?.apply {
//            if(this==1){
//                driveBlock = true
//                driveList = true
//            }else{
//                driveBlock = false
//                driveList = false
//            }
//        }

//        loginData?.member?.apps?.saleservice?.apply {
//            for (i in this) {
//                if (i.equals("1")){
//                    aftersale_maintenance = true
//                }
//                if (i.equals("2")){
//                    aftersale_drive = true
//                }
//            }
//        }
        setList()
    }

    fun setList(){
        list.clear()
        if (huashuku) {
            val app = HomeAppParam("话术库")
            app.setDrawable(R.drawable.huashuku)
            list.add(app)
        }
        if (shucaiku) {
            val app = HomeAppParam("素材库")
            app.setDrawable(R.drawable.sucaiku2)
            list.add(app)
        }
        if (calc) {
            val app = HomeAppParam("金融计算器")
            app.setDrawable(R.drawable.jinrongjisuanqi)
            list.add(app)
        }
        if (chexingduibi) {
            val app = HomeAppParam("车型对比")
            app.setDrawable(R.drawable.chexingduibi)
            list.add(app)
        }
        if (driveBlock) {
            val app = HomeAppParam("试驾看板")
            app.setDrawable(R.drawable.shijiakanban)
            list.add(app)
        }

//        if(huashuku){
//            val app = HomeAppParam("到店管理")
//            app.setDrawable(R.drawable.yy_ddgl_hs)
//            list.add(app)
//        }else {
//            if (dengji) {
//                val app = HomeAppParam("到店管理")
//                app.setDrawable(R.drawable.yy_ddgl)
//                list.add(app)
//            }
//        }
//        if(hasAuthorization) {
//            if (fail) {
//                val app = HomeAppParam("战败管理")
//                app.setDrawable(R.drawable.yy_zbgl)
//                list.add(app)
//            }
//        }
//        if(recordTable){
//            val app = HomeAppParam("语义分析")
//            app.setDrawable(R.drawable.yuyifengxi)
//            list.add(app)
//        }
//        if(analysisHui){
//            val app2 = HomeAppParam("数据分析")
//            app2.setDrawable(R.drawable.yy_sjfx_hs)
//            list.add(app2)
//        }else{
//            if(analysis) {
//                val app2 = HomeAppParam("数据分析")
//                app2.setDrawable(R.drawable.yy_sjfx)
//                list.add(app2)
//            }
//        }
//
//        if(driveBlockHui){
//            val app2 = HomeAppParam("预约看板")
//            app2.setDrawable(R.drawable.yy_sjkb)
//            list.add(app2)
//        }else{
//            if(driveBlock) {
//                val app2 = HomeAppParam("预约看板")
//                app2.setDrawable(R.drawable.yy_sjkb)
//                list.add(app2)
//            }
//        }
//
//        if(driveListHui){
//            val app2 = HomeAppParam("试驾列表")
//            app2.setDrawable(R.drawable.yy_sjlb)
//            list.add(app2)
//        }else{
//            if(driveList) {
//                val app2 = HomeAppParam("试驾列表")
//                app2.setDrawable(R.drawable.yy_sjlb)
//                list.add(app2)
//            }
//        }
//        if(calc) {
//            val app2 = HomeAppParam("购车计算器")
//            app2.setDrawable(R.drawable.yy_gcjsq)
//            list.add(app2)
//        }
//        if(orderHui){
//            val app2 = HomeAppParam("交车打卡")
//            app2.setDrawable(R.drawable.dingdanguanl_tu)
//            list.add(app2)
//        }else{
//            if(order) {
//                val app2 = HomeAppParam("交车打卡")
//                app2.setDrawable(R.drawable.dingdanguanl_tu)
//                list.add(app2)
//            }
//        }
//        if(aftersale_maintenance) {
//            val app2 = HomeAppParam("保养管理")
//            app2.setDrawable(R.drawable.bygl_tu)
//            list.add(app2)
//        }
//        if(aftersale_drive) {
//            val app2 = HomeAppParam("取送车管理")
//            app2.setDrawable(R.drawable.qscgl_tu)
//            list.add(app2)
//        }


//        val app22 = HomeAppParam("订单权益管理")
//        app22.setDrawable(R.mipmap.ddqygl)
//        list.add(app22)

        showlistData.postValue(list)
    }

    fun onClick(view: View, homeAppParam: HomeAppParam) {
        if(homeAppParam.name.equals("话术库")){
            ToastUtil.toastShortMessage("更新中...")
        }else if(homeAppParam.name.equals("素材库")){
            ToastUtil.toastShortMessage("更新中...")
        }else if(homeAppParam.name.equals("金融计算器")){
            ToastUtil.toastShortMessage("更新中...")
        }else if(homeAppParam.name.equals("车型对比")){
            ToastUtil.toastShortMessage("更新中...")
        }else if(homeAppParam.name.equals("试驾看板")){
            clickDriveBlock(view)
        }
    }

    fun onClickAnalysis(view:View){
        view.context.startActivity(Intent(view.context, AnalysisActivity::class.java))
    }
    /**
     * 点击潜客数据
     */
    fun onClickSneakGuest(view: View) {
        view.context.startActivity(Intent(view.context, SneakGuestListActivity::class.java))
    }

    /**
     * 点击库存查询
     */
    fun onClickKuCun(view: View) {
        view.context.startActivity(Intent(view.context, DriveListActivity::class.java))
    }
    /**
     * 客流接待
     */
    fun clickJiDai(view: View) {
//        view.context.startActivity(Intent(view.context, PassengerReceptionActivity::class.java))
    }

    /**
     * 到店管理
     */
    fun clickKeliu(view: View) {
//        view.context.startActivity(Intent(view.context, PassengerRegisterActivity::class.java))
        view.context.startActivity(Intent(view.context, DriveListActivity::class.java))
    }

    /**
     * 试驾看板
     */
    fun clickDriveBlock(view: View) {
        var intent = Intent(view.context, DriveBlockActivity::class.java)
        intent.putExtra("type","DriveBlock")
        view.context.startActivity(intent)
    }

    /**
     * 试驾列表
     */
    fun clickDriveList(view: View) {
        view.context.startActivity(Intent(view.context, DriveListActivity::class.java))
    }

    /**
     * 购车计算器
     */
    fun clickCacl(view:View){
        view.context.startActivity(Intent(view.context, DriveCalcActivity::class.java))
    }
//    语义分析报表
    fun clickRecordTable(view:View){
//        var intent = Intent(view.context, H5Activity::class.java)
//        intent.putExtra("url",MySharedPreferences.getLoginData()?.recordTable)
//        view.context.startActivity(intent)
        var intent = Intent(view.context, AddDriveActivity::class.java)
        view.context.startActivity(intent)
    }

    /**
     * 订单管理
     */
    fun clickOrder(view:View){
        view.context.startActivity(Intent(view.context, OrderListActivity::class.java))
    }
    /**
     * 售后管理
     */
    fun clickAfterSale(view:View){
        view.context.startActivity(Intent(view.context, AfterSaleActivity::class.java))
    }
    /**
     * 售后管理
     */
    fun clickAfterSaleDrive(view:View){
        view.context.startActivity(Intent(view.context, AfterSaleDriveActivity::class.java))
    }
    /**
     * 七日强转
     */
    fun onClickQiang(view: View) {
        var intent = Intent(view.context, OverdueActivity::class.java)
        //逾期state：1 七日强转2
        intent.putExtra("state", 2)
        view.context.startActivity(intent)
    }

    /**
     * 售后管理
     */
    fun clickOrderQuanyi(view:View){
        view.context.startActivity(Intent(view.context, OrderQuanyiActivity::class.java))
    }

    var currentContext: Context? = null
    var erModuleType:Int = 0
    /**
     * 快速估价
     */
    fun clickFastEvaluate(view:View){
        currentContext = view.context
        erModuleType = 1
        cacheCarTempInfo()
    }

    /**
     * 全面评估
     */
    fun clickEvaluate(view:View){
        currentContext = view.context
        erModuleType = 2
        cacheCarTempInfo()
    }

    private fun goChannel(moduleType:Int) {
        val loginParam = MySharedPreferences.getLoginData()
        val channelListBean = UserInfo.ChannelListBean()
        channelListBean.uid = loginParam!!.member.uid.toString() + ""
        channelListBean.channel = loginParam.member.channel.toString() + ""
        channelListBean.isadmin = 0
        channelListBean.isarchiver = 1
        channelListBean.israpid = 1
        channelListBean.isauction = 1
        channelListBean.y7e_ckey = ""

        ChannelInfoUtil.saveCurrentChannelInfo(channelListBean)

        val userData = loginParam.member
        UserInfoManager.getInstance(MyApplication.getInstance())
                .saveMobile(userData.mobile)
                .saveGender(userData.sex.toString() + "")
                .saveRealName(userData.realname)

        UserInfoManager.getInstance(MyApplication.getInstance())
                .saveY7e_ckey(channelListBean.y7e_ckey)


        if (moduleType == Constants.CURRENT_MODULE_TYPE_FAST_EVALUATE) {
            MyApplication.getInstance().setCurrentModuleType(Constants.CURRENT_MODULE_TYPE_FAST_EVALUATE)
//            startActivity(Intent(this, FastEvaluateActivity::class.java))
            currentContext?.startActivity(Intent(currentContext, FastEvaluateActivity::class.java))
        } else {
            MyApplication.getInstance().setCurrentModuleType(Constants.CURRENT_MODULE_TYPE_FULL_EVALUATE)
//            startActivity(Intent(this, EvaluateHomePageActivity::class.java))
            currentContext?.startActivity(Intent(currentContext, EvaluateHomePageActivity::class.java))
        }

    }

    private fun cacheCarTempInfo() {
        var dialog = DialogUIUtils.showLoadingHorizontal(currentContext,"加载中...").show()
        val params = java.util.HashMap<String, String>()
        params["field"] = HttpConstants.TEMP_ATTR_LIST_REQUEST_FILED
        ApiClient.postForm(HttpConstants.CAR_TEMP_ATTR_LIST, params,object : RespCallback<CarTempAttrList>() {

                    override fun onRequestFailed(msg: String) {
                        SToast.show(msg)
                        dialog.dismiss()
                    }

                    override fun onSuccess(data: CarTempAttrList?) {
                        dialog.dismiss()
                        if (null != data) {
                            SerializeUtil.saveCarTempAttrList(data)
                            MyApplication.getInstance().setAttrList(data)
                            goChannel(erModuleType)
                        }
                    }
                })
    }

//    fun checkErPermissions() {
//        DemoLog.d("checkErPermissions","start checkErPermissions")
//        val params = HashMap<String, String>()
//        val url = "HttpConstants.ER_PERMISSIONS:"+HttpConstants.ER_PERMISSIONS
//        System.out.println("HttpConstants.ER_PERMISSIONS:"+HttpConstants.ER_PERMISSIONS)
//        ApiClient.postForm(HttpConstants.ER_PERMISSIONS, params, object : RespCallback<UserPermissions>() {
//            override fun onError(call: Call, e: Exception, id: Int) {
//                bindEr()
//                if (e is UnknownHostException || e is SocketException) {
//                    return
//                }
//            }
//            override fun onRequestFailed(msg: String) {
//                bindEr()
//            }
//            override fun onSuccess(data: UserPermissions) {
//                DemoLog.d("checkErPermissions","checkErPermissions success")
//                if (null != data) {
//                    erPermission = data
//                    bindEr()
//                }
//            }
//        })
//    }

    fun showYs(view:View){
        val bottomDialog = Dialog(view.context, R.style.BottomDialog)
        val contentView = LayoutInflater.from(view.context).inflate(R.layout.dialog_content_circle, null)
        bottomDialog.setContentView(contentView)
        val params = contentView.getLayoutParams() as ViewGroup.MarginLayoutParams
        params.width = view.context.getResources().getDisplayMetrics().widthPixels - FunctionUtils.dip2px(view.context, 16f)
        params.topMargin = FunctionUtils.dip2px(view.context, 20f)
        params.bottomMargin = FunctionUtils.dip2px(view.context, 20f)
        contentView.setLayoutParams(params)
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM)
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation)
        bottomDialog.show()

        var llWin = contentView.findViewById<LinearLayout>(R.id.ll_win)
        llWin.setOnClickListener { bottomDialog.dismiss() }
    }
}